<template>
  <div class="inline-block">
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
    <el-upload
      action
      ref="upload"
      :limit="limit"
      :auto-upload="false"
      list-type="picture-card"
      :on-change="uploadVerification"
      class="inline-block img-upload"
      :on-preview="handlePictureCardPreview"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>

<script>
import { imageFormatIsCorrect } from "@/utils/image_verification.js";

export default {
  name: "Image_upload",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false
    };
  },
  methods: {
    uploadVerification(file, fileList) {
      const uploadFiles = this.$refs.upload.uploadFiles;

      if (imageFormatIsCorrect(file, this.imageMaxSize)) {
        // 图片格式、大小验证
        const isInterceptUpdoad =
          this.pegs &&
          this.pegs.length &&
          this.pegs.length + uploadFiles.length > this.limit; // 原有图片+上传的图片>最大上传数限制
        if (isInterceptUpdoad) {
          // 上传拦截
          uploadFiles.pop(); // 删除超出限制的文件
          return;
        }
        this.$refs.upload.uploadFiles = uploadFiles;
        this.$emit("uploadFiles", uploadFiles);
      } else {
        uploadFiles.pop(); // 删除超出限制的文件
      }
    },

    handlePictureCardPreview(file) {
      this.dialogVisible = true;
      this.dialogImageUrl = file.url;
    }
  },
  props: ["limit", "imageMaxSize", "pegs"]
};
</script>
 
<style scoped>
</style>